define(['jquery', 'bootstrap', 'backend','frontend', 'form', 'template','highcharts'], function ($, undefined,Backend, Frontend, Form, Template, Highcharts){
  var Controller = {
    index: function(){
      $("#u26_h").click(function(){
        $("#u26_h").attr("href","/index/quality/info"); 
      });
      $("#u31_h").click(function(){
        $("#u31_h").attr("href","/index/appquality/index"); 
      });
      $("#u34_h").click(function(){
        $("#u34_h").attr("href","/index/log/index"); 
      });
      //console.log(123);
      Controller.comprehensive();
      Controller.basedlink();
      $(document).ready(function(){
        var top = $('#top').html(),
        news = $('#news').html()

        //top10流量趋势图
        if(top == 1){
          var chart = Highcharts.chart('container', {
            chart: {
              type: 'bar'
            },
            exporting: { 
              enabled: false 
            },
            credits: { 
              enabled: false 
            },
            //启用或禁用图列
            legend: {
              enabled: false 
            },
            title: {
              text: '应用流量排行TOP10',
              style: {
                fontSize: '17px',
                fontWeight: 900
              }
            },
            xAxis: {
              categories: [],
              title: {
                text: null
              }
            },
            yAxis: {
              min: 0,
              title: {
                text: '流量(G)',
              },
              labels: {
                overflow: 'justify',
              },
            },
            tooltip: {
              valueSuffix: ' '
            },
            plotOptions: {
              bar: {
                dataLabels: {
                  enabled: true,
                  allowOverlap: true // 允许数据标签重叠
                }
              },
            },
            series: [{
              name: '流量(G)',
              data: []
            }]
          });
          $.ajax({ 
            url: "/index/home/info", 
            type: 'post',
            dataType: 'json',
            success: function(res){
              var d = JSON.parse(res);
              if(d.code == 401){
                Backend.api.toastr.error(d.msg);
                return false;
              }
              var datas = d.data;
              //console.log(datas);
              var categories=[];
              var data = [];
              for(var i = 0; i<datas.length;i++){
                var register = datas[i].name;
                var value = Number(datas[i].value)/1024/1024/1024;
                value = value.toFixed(2);
                categories[i] = register;
                data[i] = Number(value);
              }
              chart.xAxis[0].setCategories(categories);
              chart.series[0].setData(data);
            } 
          });
        }

          //新版本上下行流量趋势

           
        if(news ==  1){
            $.ajax({
              url: '/index/home/new_flow',
              type:'post',
              dataType:'json',
              success:function(json){              
                  var data = JSON.parse(json)
                  if(data.code == 401){
                    Backend.api.toastr.error(data.msg);
                    //return false;
                }
                if(data.code == 0 || data.code == 403){
                  options = {
                      positionClass: "toast-top-center",
                  };
                  Backend.api.toastr.error(data.msg,'',options);
                  //return false;
                }
                var time = []
                    up   = []
                    down = []
                for(var index in data.data){
                    var art = new Date(data.data[index].key)
                        row = art.getHours()+':'+art.getMinutes()
                        up_flow =  Number((data.data[index].up.value / 1024 /1024).toFixed(2))
                        down_flow = Number((data.data[index].down.value / 1024 /1024).toFixed(2))
                    time.push(row);
                    up.push(up_flow);
                    down.push(down_flow);
                }

                Highcharts.chart('containers',{
                  chart: {
                    type: 'areaspline'
                  },
                  title: {
                    text: '24小时流量趋势图',
                    style: {
                      fontSize: '17px',
                      fontWeight: 900
                    }
                  },

                  legend: {
                    layout: 'vertical',
                    align: 'left',
                    verticalAlign: 'top',
                    x: 150,
                    y: 100,
                    floating: true,
                    borderWidth: 1,
                    backgroundColor: (Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'
                  },

                  xAxis: {
                    categories: time,
                  },
                  yAxis: {
                    title: {
                      text: 'bits/s'
                    },
                    labels: {
                      formatter: function () {
                        return this.value+'M';
                      }
                    }
                  },
                  credits: {
                    enabled: false
                  },
                  tooltip: {
                    crosshairs: true,
                    shared: true
                  },
                  plotOptions: {
                    spline: {
                      marker: {
                        radius: 4,
                        lineColor: '#666666',
                        lineWidth: 1
                      }
                    }
                  },
                  series: [{
                    name: '下行流量',
                    data: down
                  }, {
                    name: '上行流量',
                    data: up
                  }]

                })

              }
            });
        }
      });


    },
    //  大屏首页
    big_index: function(){
      setInterval(function(){
        Controller.getDate()
      }, 1000);        
    },

      //综合质量
      comprehensive: function() {
        $.ajax({
          url: '/index/home/comprehensive',
          type:'post',
          dataType:'json',
          success:function(json){        
              Controller.rendering(json);          
          }
        });
      },
    
      rendering: function(json){

        var json = JSON.parse(json)
        //console.log(json);
        if(json.code == 401){
            Backend.api.toastr.error(json.msg);
            return false;
        }
        if(json.code == 0 || json.code == 403){
          $("#u26_text span").html(0);
          $("#u31_text span").html(0);
          $("#u34_text span").html(0);
          options = {
              positionClass: "toast-top-center",
          };
          Backend.api.toastr.error(json.msg,'',options);
          return false;
        }
          var app_qualitys = Math.round(json.data.app_quality);
          if(app_qualitys === -1){
              app_qualitys= 0
          }
          if(json.data.quality == -1){
            json.data.quality = 0
          }
          $("#u26_text span").html(json.data.quality);
          $("#u31_text span").html(app_qualitys);
          //判断故障日志是否有
          if(typeof(json.data.breakdown) != 'undefined'){
            if(Number(json.data.breakdown)>120){
              json.data.breakdown = 120
            }
            $("#u34_text span").html(json.data.breakdown);
          }
		      if(typeof(json.data.breakdown_quality) != 'undefined'){
            switch(json.data.breakdown_quality){
                case '优' :
                $("#u33_img").attr("src","/assets/img/frontend/home/u25.png");
                break;
                case '良' :
                $("#u33_img").attr("src","/assets/img/frontend/home/u29.png");
                break;
                case '差' :
                $("#u33_img").attr("src","/assets/img/frontend/home/u28.png");
                break;
                default :
                $("#u33_img").attr("src","/assets/img/frontend/home/u27.png");
            }
          }
          switch(json.data.appqualitys){
            case '-':
            $("#u30_img").attr("src","/assets/img/frontend/home/u25.png");
            break;
            case '好' :
            $("#u30_img").attr("src","/assets/img/frontend/home/u25.png");
            break;
            case '较好' :
            $("#u30_img").attr("src","/assets/img/frontend/home/u25.png");
            break;
            case '警告' :
            $("#u30_img").attr("src","/assets/img/frontend/home/u29.png");
            break;
            case '较差' :
            $("#u30_img").attr("src","/assets/img/frontend/home/u28.png");
            break;
            default :
            $("#u30_img").attr("src","/assets/img/frontend/home/u27.png");
          }

          

      },








    //基础质量链路图
    basedlink: function () {
        $.ajax({
            url: '/index/quality/basedlink',
            type:'post',
            data: {propertyname: 'basedlink'},
            dataType:'json',
            success:function(json){                 
                Controller.piechart(json, "qualityScore", "basedlink");                    
            }
        });
    },






    piechart: function(json, type, id){ //画图 饼图/趋势图   数据   类型(画图的字段后期可扩展)  id
      var toolTipValue="";
      var text = "";
      if(id == 'webpage' ){
          text = '网页测试';
      }else if(id == 'filedownload'){
          text = '下载速率';
      }else if(id == 'basedlink'){
          text = '基础链路';
      }

      if (type == "firstFramesTime") {
          text += '首帧时长(平均值)指标趋势图';
          toolTipValue = "首帧时长";
      } else if (type == "firstVideoTime") {
          text += '总缓冲时长(平均值)指标趋势图';
          toolTipValue = "总缓冲时长";
      } else if(type == "downloadSpeed"){
          text += '下载速率(平均值)指标趋势图';
          toolTipValue = "下载速率";
      } else if(type == "totalBufferNumber"){
          text += '总缓冲次数(平均值)指标趋势图';
          toolTipValue = "总缓冲次数";
      } else if(type == "blankScreen"){
          text += '黑屏(平均值)指标趋势图';
          toolTipValue = "黑屏";
      } else if(type == "qualityScore"){
          text += '质量分趋势图';
          toolTipValue = "质量分";
      }

      if(json.code == 401){
          Backend.api.toastr.error(json.msg);
          window.location.href='/index/user/login';
          return false;
      }

      if(json.code == 0 || json.code == 403){
          // alert(msg);
          options = {
              positionClass: "toast-top-center",
          };
          Backend.api.toastr.error(text+json.msg,'',options);
          return false;
      }
      Highcharts.chart(id, {
          chart: {
              // zoomType: 'x',
              // type: 'area'
          },
          title: {
              style: {
                  // color: 'red',   //字体颜色
                  fontSize:"14px", //字体大小
                  "font-weight": "bold",
              },
              text: text,
              style: {
                  // color: 'red',   //字体颜色
                  fontSize:"17px", //字体大小
                  "font-weight": "bold",
              },
              x: -20 //center
          },

          credits: {
              enabled: false
          },           
          xAxis: {
              //tickInterval: -2,//刻度的宽度,
              categories : json.xAxis,
              labels:{
                  x:15
              },
          },
          yAxis: {
              title: {
                  text: null,
              },
              labels: {
                formatter:function(){
                    return this.value;
                }
              },
              plotLines: [{
                  value: 0,
                  width: 1,
                  color: '#808080'
              }],
              // min:0,
              //tickInterval: 5//刻度的宽度       
              tickPositions: [0, 20, 40, 60, 80,100] // 指定竖轴坐标点的值         
          },
          legend: {
              //enabled: false   //隐藏图例
          },
          tooltip : {
              formatter : function() {
                  if(type=="001"&&id=="blankScreen"){
                      if(this.point.y=="0.00"){
                          return '<b>' + this.series.name + '</b><br>时间:' + this.key + '<br>'+toolTipValue+'：' + "否";
                      }else{
                          return '<b>' + this.series.name + '</b><br>时间:' + this.key + '<br>'+toolTipValue+'：' + "是";
                      }
                  }
                  else
                      return '<b>' + this.series.name + '</b><br>时间:' + this.key + '<br>'+toolTipValue+'：' + this.point.y;
              }
          },                    
          // series:[{
          //     seriesshowInLegend: false,   //隐藏数据名称
          //     type :'area',
          //     name:'网信',
          //     data:json.series
          // }]
          series: json.series
      });            
  },

      //单位装换
      number: function(num){
        if (num >= 1024 * 1024 * 1024)
                return ((num / (1024 * 1024 * 1024))).toFixed(2) + 'G';
        else
        if (num >= 1024 * 1024)
                return ((num / (1024 * 1024))).toFixed(2) + 'M';
        else     
        if (num >= 1024)
                return ((num / 1024)).toFixed(2) + 'K';
        else
                return num;
      },
      getDate:function(){
        console.log(123);
        var today = new Date();  
        var date = today.getFullYear() + "-" + Controller.twoDigits(today.getMonth() + 1) + "-" + Controller.twoDigits(today.getDate()) + " ";  
        var week = " 星期" + "日一二三四五六 ".charAt(today.getDay());  
        var time = Controller.twoDigits(today.getHours()) + ": " + Controller.twoDigits(today.getMinutes()) + ": " + Controller.twoDigits(today.getSeconds());
        $("#time_span").text(date +" "+time);
      },
      twoDigits:function(val){
        if (val < 10) return "0" + val; return val;
      },

      

  }






  return Controller;
});
